package com.fablesoft.projectdatacollect.ui;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.mining.app.zxing.camera.CameraManager;
import com.mining.app.zxing.decoding.CaptureActivityHandler;
import com.mining.app.zxing.decoding.InactivityTimer;
import com.mining.app.zxing.view.ViewfinderView;

public class MipcaActivityCapture extends BaseRequestActivity implements
		Callback {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.30f;
	private boolean vibrate;
	private String xmid;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
		// ViewUtil.addTopView(getApplicationContext(), this,
		// R.string.scan_card);
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
		initTitleView();
	}

	private void initTitleView() {
		getTitleBack().setVisibility(View.VISIBLE);
		getTitleName().setText(R.string.saoma_title);
		getTitleBack().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
			surfaceHolder.addCallback(this);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = false;

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		if (mediaPlayer != null) {
			mediaPlayer.release();
		}
		super.onDestroy();
	}

	/**
	 * 处理扫描结果
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();
		if (TextUtils.isEmpty(resultString)) {
			Toast.makeText(MipcaActivityCapture.this, "Scan failed!",
					Toast.LENGTH_SHORT).show();
			return;
		}
//		Intent intent = null;
//		String[] results = resultString.split("_");
//		if ("1".equals(results[0])) {
//			intent = new Intent(this, LeagueDetailActivity.class);
//			intent.putExtra("leagueId", results[1]);
//			startActivity(intent);
//			finish();
//		} else if ("2".equals(results[0])) {
//			intent = new Intent(this, MediationDetailActivity.class);
//			intent.putExtra("userType", 4);
//			intent.putExtra("userid", results[1]);
//			startActivity(intent);
//			finish();
//		} else if ("3".equals(results[0])) {
//			intent = new Intent(this, ServiceProjectDetailActivity.class);
//			intent.putExtra("xmid", results[1]);
//			startActivity(intent);
//			finish();
//		} else if ("4".equals(results[0])) {
//			xmid = results[1];
//			Map<String, String> params = new HashMap<String, String>();
//			params.put("xmid", xmid);
//			createLoadingDialog(this);
//			showDialog("签到中");
//			sendRequest(Config.SIGN_IN_URL, params, BaseResponse.class);
//		}
	}

//	private Handler mHandler = new Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			dismissDialog();
//			if (msg.obj == null) {
////				Toast.makeText(MipcaActivityCapture.this,
////						R.string.request_error, Toast.LENGTH_SHORT).show();
//				createConfirmDialog(
//						MipcaActivityCapture.this,
//						null,
//						getResources().getString(R.string.sign_in_error_tip), 
//						null,null, null);
//			} else {
//				BaseResponse response = (BaseResponse) msg.obj;
//				if ("01100017".equals(response.getErrorcode())) {
//					createConfirmDialog(
//							MipcaActivityCapture.this,
//							null,
//							getResources().getString(
//									R.string.no_sign_for_no_start),
//							null,
//							getResources().getString(R.string.see_project),
//							new ConfirmClickListener() {
//								@Override
//								public void confirmClickImp() {
//									Intent intent = new Intent(
//											MipcaActivityCapture.this,
//											ServiceProjectDetailActivity.class);
//									intent.putExtra("xmid", xmid);
//									startActivity(intent);
//									finish();
//								}
//							});
//				} else if ("01100018".equals(response.getErrorcode())) {
//					createConfirmDialog(
//							MipcaActivityCapture.this,
//							null,
//							getResources().getString(
//									R.string.no_sign_for_no_join_tip), null,
//							null, null);
//				} else {
//					createConfirmDialog(
//							MipcaActivityCapture.this,
//							null,
//							response.getMessage(), null,
//							null, null);
////					Toast.makeText(MipcaActivityCapture.this,
////							response.getMessage(), Toast.LENGTH_SHORT).show();
//				}
//			}
//		};
//	};

	protected void createConfirmDialog(Activity mContext, String title,
			String content, String confirmStr, String cancelStr,
			final ConfirmClickListener leftConfirmListener) {

		final Dialog dialog = new Dialog(mContext,
				R.style.Theme_Light_CustomDialog);
		dialog.setContentView(R.layout.prompt_dialog_layout);
		dialog.setCanceledOnTouchOutside(false);
		WindowManager m = mContext.getWindowManager();
		Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
		WindowManager.LayoutParams p = dialog.getWindow().getAttributes(); // 获取对话框当前的参数值
		p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.8
		dialog.getWindow().setAttributes(p);
		TextView promptTitle = (TextView) dialog
				.findViewById(R.id.prompt_title);
		TextView promptContent = (TextView) dialog
				.findViewById(R.id.prompt_content);
		TextView confirmBtn = (TextView) dialog.findViewById(R.id.confirm_btn);
		TextView cancelBtn = (TextView) dialog.findViewById(R.id.cancel_btn);
		if (!TextUtils.isEmpty(title)) {
			promptTitle.setText(title);
		}
		if (!TextUtils.isEmpty(content)) {
			promptContent.setText(content);
		}
		if (!TextUtils.isEmpty(confirmStr)) {
			confirmBtn.setText(confirmStr);
		}
		if (!TextUtils.isEmpty(cancelStr)) {
			cancelBtn.setText(cancelStr);
		}
		OnClickListener dialogOnClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.cancel_btn:
					if (leftConfirmListener != null) {
						leftConfirmListener.confirmClickImp();
					}
					dialog.dismiss();
					break;
				case R.id.confirm_btn:
					dialog.dismiss();
					break;
				}
			}
		};
		if(TextUtils.isEmpty(cancelStr)){
			cancelBtn.setVisibility(View.GONE);
			LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mLayoutParams.setMargins(getResources().getDimensionPixelSize(R.dimen.ui_60_dip), 0, getResources().getDimensionPixelSize(R.dimen.ui_60_dip), 0);
			confirmBtn.setLayoutParams(mLayoutParams);
		}else{
			cancelBtn.setOnClickListener(dialogOnClickListener);
		}
		confirmBtn.setOnClickListener(dialogOnClickListener);
		dialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				if (handler != null) {
					handler.restartPreviewAndDecode();
				}
			}
		});
		dialog.show();
	}

//	@Override
//	public void onRequestFinish(BaseResponse response) {
//		Message msg = mHandler.obtainMessage();
//		msg.obj = response;
//		mHandler.sendMessage(msg);
//	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			Log4jUtil.e(ioe.toString());
			return;
		} catch (RuntimeException e) {
			Log4jUtil.e(e.toString());
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = MediaPlayer.create(this, R.raw.beep);
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);
			mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
			// try {
			// mediaPlayer.prepare();
			// } catch (IllegalStateException e) {
			// e.printStackTrace();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		@Override
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
}